package ru.sharaf.selenium.pages;

import static org.openqa.selenium.support.ui.ExpectedConditions.*;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.TimeoutException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;

import ru.sharaf.selenium.model.Film;

/**
 * Главная страница каталога.
 */

public class InternalPage extends AnyPage {

  public InternalPage(PageManager pages) {
	super(pages);
  }
	
  public InternalPage ensurePageLoaded() {
    super.ensurePageLoaded();
    wait.until(presenceOfElementLocated(By.cssSelector("nav")));
    return this;
  }
  
  public void searchFilm(String movie){
	  searchInput.clear();
	  searchInput.sendKeys(movie);
	  searchInput.sendKeys(Keys.RETURN);
  }
  
  public boolean isMovieNotFound(){
  try {
      wait.until(presenceOfElementLocated(By.xpath("//div[@class='content' and text()='No movies where found.']")));
      return true;
	 } catch (TimeoutException to) {
	      return false;
	    }
  }
  
  public boolean isMovieFound(String title){
  try {
      wait.until(presenceOfElementLocated(By.xpath("//div[@class='title' and text()='"+ title + "']")));
      return true;
	 } catch (TimeoutException to) {
	      return false;
	    }
  }

  @FindBy(css = "nav a[onclick $= '?logout']")
  private WebElement logoutLink;
  
  @FindBy(xpath = "//input[@id='q']")
  private WebElement searchInput;	
  
  @FindBy(xpath = "//div[@class='content' and text()='No movies where found.']")
  private WebElement noSuchMovie;	  
  
  @FindBy(css = "img[alt=\"Update all\"]")
  private WebElement updateAll;
  
  @FindBy(css = "img[alt='Add movie']")
  private WebElement addButton;
  
  @FindBy(xpath = "//a[text()='Home']")
  private WebElement homeLink;
  
  @FindBy(css = "nav a[href $= '?go=profile']")
  private WebElement userProfileLink;

  @FindBy(css = "nav a[href $= '?go=users']")
  private WebElement userManagementLink;

  /** Найти элемент по xpath */
  public WebElement getWebElement(Film film, String elementClass, String order){
	  return wait.until(presenceOfElementLocated(By.xpath("(//div[@class='" + elementClass + "' and @title='"
					+ film.getTitle() + "'])[" + order +"]")));
  }
  
  public LoginPage clickLogoutLink() {
    logoutLink.click();
    wait.until(alertIsPresent()).accept();
    return pages.loginPage;
  }
 
 public InternalPage updateAllClick(){
	 updateAll.click();
	 return pages.internalPage;
 }
 
 public void addButtonClick(){
	 addButton.click();
 }
 
 public void clickHomeLink(){
	 homeLink.click();
 }
  
}
